#! /usr/bin/python
# coding=utf-8
import time
import os,sys,stat
import ConfigParser

script_path=os.path.dirname(sys.argv[0])
config_file=os.path.join(script_path,'config.ini')
tun0_ip="10.2.2.10"
ptp_ip="10.2.2.9"
eth0_ip="192.168.2.11"
wlan0_segment="192.168.10.0/24"
if len(sys.argv)==5:
	_c=sys.argv
	_c.pop(0)
	tun0_ip,ptp_ip,eth0_ip,wlan0_segment=_c
if os.path.isfile(config_file):
	cf = ConfigParser.ConfigParser()
	cf.read(config_file)
	if cf.has_section('ip'):
		tun0_ip=cf.get('ip','vpn_ip')
		ptp_ip= cf.get('ip','ptp')
		eth0_ip=cf.get('ip','eth0_ip')
		wlan0_segment=cf.get('ip','wlan0_ip')

 
route_file="route.txt"
route_file=os.path.realpath(script_path+os.sep+route_file)

print route_file

linux_route_tpl="route add -net %s gw "+ptp_ip#+" dev tun0"
linux_nat_tpl="iptables -t nat -A POSTROUTING -s "+wlan0_segment+"  %s -j SNAT  --to-source %s"

result_route=["#! /bin/sh"]
result_nat=["#! /bin/sh"]

for line in open(route_file,'r'):
    line=line.strip()
    #print line.find("#")
    #exit
    if line=="" or line.find("#")>=0:
        continue
    result_route.append(linux_route_tpl%(line,))
    result_nat.append(linux_nat_tpl%("--dst "+line,tun0_ip))
    
linux_route=script_path+os.sep+'linux_route.sh';
linux_nat=script_path+os.sep+'linux_nat.sh';

f=open(linux_route,'w')
f.write("\n".join(result_route))
f.close()

#nat

_nat="iptables -t nat -F \n"#清空原有NAT规则
result_nat.insert(1,_nat)

_nat="#def NAT \n"+linux_nat_tpl%("",eth0_ip)+"\n"#默认转发规则
result_nat.append(_nat)

f=open(linux_nat,'w')
f.write("\n".join(result_nat))
f.close()

os.chmod(linux_route,stat.S_IRWXU)
os.chmod(linux_nat,stat.S_IRWXU)
 
print "linux_route.sh 及 linux_nat.sh 已经生成 请运行"
